import os
import sys
from tqdm import tqdm
import gradio as gr
# set cache folder 
os.environ["TRANSFORMERS_CACHE"] = os.getcwd()+"/hub"
os.environ["HF_HUB_OFFLINE"] ="YES"
os.environ["TRANSFORMERS_OFFLINE"] ="YES"
# system pwd
sys.path.append(os.path.join(os.getcwd(), "GroundingDINO"))
sys.path.append(os.path.join(os.getcwd(), "segment_anything"))

import torch
import cv2
import argparse
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from PIL import Image
import json


# Grounding DINO
import GroundingDINO.groundingdino.datasets.transforms as T
from GroundingDINO.groundingdino.models import build_model
from GroundingDINO.groundingdino.util.slconfig import SLConfig
from GroundingDINO.groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap

# SAM
from segment_anything import sam_model_registry,SamPredictor



## Hyp
grounding_caption_list = ["white line.","sign.","Road."]
caption_color = {
    "white line.": np.array([30/255, 144/255, 255/255, 0.6]),
    "sign.":np.array([60/255, 122/255, 255/255, 0.6]),
    "Road.":np.array([90/255, 66/255, 255/255, 0.6]),
}
device = 'cpu' 
bert_base_uncased_path = 'bert-base-uncased'
config_file = "GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py"  # change the path of the model config file
grounded_checkpoint = "groundingdino_swint_ogc.pth"  # change the path of the model
sam_version = "vit_h"
sam_checkpoint = "sam_vit_h_4b8939.pth"
output_dir = "test"
video_fmt = [".mp4",".avi"]
image_fmt = [".png",".jpg"]

### utils
def load_ground_model(model_config_path, model_checkpoint_path, bert_base_uncased_path, device):
    args = SLConfig.fromfile(model_config_path)
    args.device = device
    args.bert_base_uncased_path = bert_base_uncased_path
    model = build_model(args)
    checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
    load_res = model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
    print(load_res)
    _ = model.eval()
    return model

def load_image(input_image):
    if isinstance(input_image,str) or isinstance(input_image,Path):
        image_pil = Image.open(input_image).convert("RGB")  # load image
    elif isinstance(input_image,np.ndarray):
        image_pil = Image.fromarray(cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB))
   
    transform = T.Compose(
        [
            T.RandomResize([800], max_size=1333),
            T.ToTensor(),
            T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
        ]
    )
    image, _ = transform(image_pil, None)  # 3, h, w
    return image_pil, image

def get_grounding_output(image, caption, box_threshold, text_threshold, with_logits=True, device="cpu"):
    caption = caption.lower()
    caption = caption.strip()
    if not caption.endswith("."):
        caption = caption + "."
    model = ground_model.to(device)
    image = image.to(device)
    with torch.no_grad():
        outputs = model(image[None], captions=[caption])
    logits = outputs["pred_logits"].cpu().sigmoid()[0]  # (nq, 256)
    boxes = outputs["pred_boxes"].cpu()[0]  # (nq, 4)
    logits.shape[0]

    # filter output
    logits_filt = logits.clone()
    boxes_filt = boxes.clone()
    filt_mask = logits_filt.max(dim=1)[0] > box_threshold
    logits_filt = logits_filt[filt_mask]  # num_filt, 256
    boxes_filt = boxes_filt[filt_mask]  # num_filt, 4
    logits_filt.shape[0]

    # get phrase
    tokenlizer = model.tokenizer
    tokenized = tokenlizer(caption)
    # build pred
    pred_phrases = []
    for logit, box in zip(logits_filt, boxes_filt):
        pred_phrase = get_phrases_from_posmap(logit > text_threshold, tokenized, tokenlizer)
        if with_logits:
            pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
        else:
            pred_phrases.append(pred_phrase)

    return boxes_filt, pred_phrases

def show_mask(mask, ax, caption,random_color=False):
    if random_color:
        color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
    else:
        color = caption_color[caption]
    h, w = mask.shape[-2:]
    mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
    ax.imshow(mask_image)

def show_box(box, ax, label):
    x0, y0 = box[0], box[1]
    w, h = box[2] - box[0], box[3] - box[1]
    ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
    ax.text(x0, y0, label)


def save_mask_data(output_dir, mask_list, box_list, label_list):
    value = 0  # 0 for background

    mask_img = torch.zeros(mask_list.shape[-2:])
    for idx, mask in enumerate(mask_list):
        mask_img[mask.cpu().numpy()[0] == True] = value + idx + 1
    plt.figure(figsize=(10, 10))
    plt.imshow(mask_img.numpy())
    plt.axis('off')
    plt.savefig(os.path.join(output_dir, 'mask.jpg'), bbox_inches="tight", dpi=300, pad_inches=0.0)

    json_data = [{
        'value': value,
        'label': 'background'
    }]
    for label, box in zip(label_list, box_list):
        value += 1
        name, logit = label.split('(')
        logit = logit[:-1] # the last is ')'
        json_data.append({
            'value': value,
            'label': name,
            'logit': float(logit),
            'box': box.numpy().tolist(),
        })
    with open(os.path.join(output_dir, 'mask.json'), 'w') as f:
        json.dump(json_data, f)

    return mask_img.numpy()


# build model
print("==>build model...")
ground_model = load_ground_model(config_file, grounded_checkpoint, bert_base_uncased_path, device=device)
sam_model = SamPredictor(sam_model_registry[sam_version](checkpoint=sam_checkpoint).to(device))


def video_identity(input_video, box_threshold, text_threshold):
    # 1. 读取视频文件
    cap = cv2.VideoCapture(input_video)
    
    # 2. 获取视频的基本信息
    fps = cap.get(cv2.CAP_PROP_FPS)  # 获取视频帧率
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))  # 获取视频的宽度
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))  # 获取视频的高度
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))  # 获取视频的总帧数
    
    # 3. 视频编码设置
    fourcc = cv2.VideoWriter_fourcc(*'XVID')  # 视频编码格式 (XVID 编码)
    out_video_path = f"{output_dir}/output_video.mp4"
    out = cv2.VideoWriter(out_video_path, fourcc, fps, (frame_width, frame_height))  # 初始化 VideoWriter

    print("start process\n")
    # for i in progress.tqdm(range(total_frames)):
    with tqdm(total=total_frames, desc="Processing Video", unit="frame") as pbar:
        while cap.isOpened():   
            ret, frame = cap.read()
            if not ret:
                break
            
            
            # 调用 Grounding DINO 进行检测
            for caption in grounding_caption_list:
                frame = process_imgae(frame,caption,box_threshold, text_threshold,is_mask=False)

            frame_with_box = cv2.resize(frame,(frame_width,frame_height))
            
            print(frame_with_box.shape)
            out.write(frame_with_box)
            
            # 更新进度条
            pbar.update(1)
            # i+=1
            # print(f"fin {i} frame")
    
    cap.release()
    out.release()
    
    print("Video processing completed.")
    return out_video_path

def pipeline(image_bgr, box_threshold, text_threshold):
    cur_image = image_bgr.copy()
    for caption in grounding_caption_list:
        cur_image = process_imgae(cur_image,caption,box_threshold, text_threshold,is_mask=False)
    return cur_image



def process_imgae(image_bgr, caption, box_threshold, text_threshold,is_mask= True):
    image_pil, image = load_image(image_bgr)
    # run grounding dino model
    boxes_filt, pred_phrases = get_grounding_output(image, caption, box_threshold, text_threshold, device=device)


    # if not is_mask:
    #     return
    # image_bgr = cv2.imread(str(image_path))
    image_RGB = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
    sam_model.set_image(image_RGB)

    size = image_bgr.shape
    H, W = size[0], size[1]
    for i in range(boxes_filt.size(0)):
        boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])
        boxes_filt[i][:2] -= boxes_filt[i][2:] / 2
        boxes_filt[i][2:] += boxes_filt[i][:2]

    boxes_filt = boxes_filt.cpu()
    transformed_boxes = sam_model.transform.apply_boxes_torch(boxes_filt, image_bgr.shape[:2]).to(device)

    masks, _, _ = sam_model.predict_torch(
        point_coords = None,
        point_labels = None,
        boxes = transformed_boxes.to(device),
        multimask_output = False,
    )

    # draw output image
    plt.figure(figsize=(10, 10))
    plt.imshow(image_RGB)
    for mask in masks:
        show_mask(mask.cpu().numpy(), plt.gca(),caption, random_color=False)
    # for box, label in zip(boxes_filt, pred_phrases):
    #     show_box(box.numpy(), plt.gca(), label)

    plt.axis('off')
    tmp_file  = "grounded_sam_output.jpg"
    plt.savefig(
        os.path.join(output_dir, tmp_file),
        bbox_inches="tight", dpi=300, pad_inches=0.0
    )


    save_mask_data(output_dir, masks, boxes_filt, pred_phrases)
    # images = plt.gca().get_images() 
    return  cv2.imread(os.path.join(output_dir, tmp_file))


if __name__ == "__main__":
    with gr.Blocks() as demo:
        with gr.Row():
            with gr.Column():
                input_image = gr.Image()
                # grounding_caption = gr.Textbox(label="Detection Prompt")
                run_button = gr.Button()
                with gr.Accordion("Advanced options", open=False):
                    box_threshold = gr.Slider(
                        label="Box Threshold", minimum=0.0, maximum=1.0, value=0.25, step=0.001
                    )
                    text_threshold = gr.Slider(
                        label="Text Threshold", minimum=0.0, maximum=1.0, value=0.25, step=0.001
                    )

            with gr.Column():
                output_image = gr.Image()

        run_button.click(fn=pipeline, inputs=[
                input_image, box_threshold, text_threshold], outputs=output_image)
    demo.launch()

    